//
//  PlayDeviceSelectViewController.m
//  wAudioShare
//
//  Created by 赵帅 on 14-1-11.
//  Copyright (c) 2014年 赵帅. All rights reserved.
//

#import "PlayDeviceSelectViewController.h"
#import "SurDataShareObj.h"
#import "SurGroupObject.h"
#import "MMProgressHUD.h"

@interface PlayDeviceSelectViewController ()
<servicePlayListDemoDelegate>
{
    NSMutableArray * dataArray;
    
    NSMutableArray * selectedArray;
    
    NSMutableArray * allDeviceArray;//所有设备的信息
    NSMutableArray * selectedIPArray;
}

@property (assign) IBOutlet UITableView * tableView;

@end

@implementation PlayDeviceSelectViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    selectedArray = [[NSMutableArray alloc] init];
    dataArray = [NSMutableArray array];
    allDeviceArray = [NSMutableArray array];
    
    for(SurGroupObject * obj in [SurDataShareObj sharedInstance].groupArray)
    {
        [dataArray addObject:obj];
    }
    
    for(NSDictionary * dic in [SurDataShareObj sharedInstance].allDeviceArray)
    {
        [dataArray addObject:dic];
        
        //取出所有名称、ip
        [allDeviceArray addObject:dic];
    }

    [self prepareUI];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
#pragma mark UITableView Delegate & Datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [dataArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }
    else
    {
        for(UIView * subview in [cell.contentView subviews])
        {
            [subview removeFromSuperview];
        }
    }
    
    // Configure the cell.
    id obj = [dataArray objectAtIndex:indexPath.row];
    
    UILabel * titleLabel = [[UILabel alloc] init];
    UIImageView * imagev = [[UIImageView alloc] initWithFrame:CGRectMake(25, 15, 30, 30)];
    
    if([obj isKindOfClass:[SurGroupObject class]])
    {
        SurGroupObject * temp = (SurGroupObject *)obj;
        
        titleLabel.frame = CGRectMake(65, 10, 195, 40);
        titleLabel.text = temp.groupName;
        
        imagev.image = [UIImage imageNamed:@"multiroom_group"];
    }
    else
    {
        NSDictionary * temp = (NSDictionary *)obj;
        
        titleLabel.frame = CGRectMake(65, 10, 195, 40);
        titleLabel.text = temp[@"name"];
        
        imagev.image = [UIImage imageNamed:@"topAnimation_device"];
    }
    
    [cell.contentView addSubview:imagev];
    [cell.contentView addSubview:titleLabel];
    
    if([self isItemSelected:obj])
    {
        UIImageView * rightImage = nil;
        rightImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"chosen.png"]];
        rightImage.frame = CGRectMake(tableView.frame.size.width-45, 20, 20, 20);
        [cell.contentView addSubview:rightImage];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:YES];
    
    id obj = dataArray[indexPath.row];
    
    BOOL isExsit = NO;
    id temp = nil;
    for(temp in selectedArray)
    {
        if(temp == obj)
        {
            isExsit = YES;
            break;
        }
    }
    
    if(isExsit == YES)
    {
        [selectedArray removeObject:obj];
    }
    else
    {
        [selectedArray addObject:obj];
    }
    
    [self.tableView reloadData];
}

#pragma mark - private methods
-(BOOL)isItemSelected:(id)item
{
    for(id tempDic in selectedArray)
    {
        if(item == tempDic) return YES;
    }
    return NO;
}

-(void)prepareUI
{
    UIButton *confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [confirmButton setTitle:@"确定" forState:UIControlStateNormal];
    [confirmButton addTarget:self action:@selector(confirmButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [confirmButton setBackgroundImage:[UIImage imageNamed:@"normalbutton_normal"]
                             forState:UIControlStateNormal];
    [confirmButton setBackgroundImage:[UIImage imageNamed:@"normalbutton_press"]
                             forState:UIControlStateHighlighted];
    confirmButton.frame = CGRectMake(0, 0, 73, 38);
    
    UIBarButtonItem* rightBtnItem = [[UIBarButtonItem alloc] initWithCustomView:confirmButton];
    self.navigationItem.rightBarButtonItem = rightBtnItem;
}

-(IBAction)confirmButtonPressed:(id)sender
{
    if([selectedArray count] == 0)
    {
        UIAlertView * av = [[UIAlertView alloc] initWithTitle:@"提示"
                                                      message:@"请至少选择一个设备"
                                                     delegate:nil
                                            cancelButtonTitle:@"确定"
                                            otherButtonTitles:nil];
        [av show];
        
        return;
    }
    
    selectedIPArray = [NSMutableArray array];
    
    for(id obj in selectedArray)
    {
        if([obj isKindOfClass:[SurGroupObject class]])
        {
            SurGroupObject * temp = (SurGroupObject *)obj;
            
            for(NSString * name in temp.audioGroup)
            {
                [self addDeviceIPToFinalArray:name];
            }
        }
        else
        {
            NSDictionary * temp = (NSDictionary *)obj;
            [self addDeviceIPToFinalArray:temp[@"name"]];
        }
    }
    
    [[GlobalService sharedInstance] playListDemo:self musicURL:self.musicName masterIP:selectedIPArray[0] groupName:selectedIPArray];
    
    [MMProgressHUD showWithStatus:@"请求发送中"];
}

-(NSString *)getIPWithName:(NSString *)name
{
    for(NSDictionary * dic in allDeviceArray)
    {
        if([dic[@"name"] isEqualToString:name])
        {
            return dic[@"ip"];
        }
    }
    
    return nil;
}

-(void)addDeviceIPToFinalArray:(NSString *)deviceName
{
    NSString * ipStr = [self getIPWithName:deviceName];
    if([ipStr length] != 0)
    {
        if([ipStr length] == 0) return;
        
        BOOL isExsit = NO;
        for(NSString * ip in selectedIPArray)
        {
            if([ip isEqualToString:ipStr])
            {
                isExsit = YES;
                break;
            }
        }
        
        if(isExsit == NO)
        {
            [selectedIPArray addObject:ipStr];
        }
    }
}

#pragma mark - navigation methods
-(NSString *)navigationBarTitle
{
    return @"Surrounder";
}

-(void)servicePlayListDemoCallBack:(NSDictionary*)dicCallBack
{
    if([[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_SUCCESS intValue])
    {
        [MMProgressHUD dismissWithSuccess:@"请求发送成功"];
        
        [self.navigationController popViewControllerAnimated:YES];
    }
    else
    {
        [MMProgressHUD dismissWithError:@"播放失败"];
    }
}

@end
